<template>
  <div class="home">
    <!-- 导航 -->
    <NavBar title="BDC" isFixed />
    <div class="contentview" v-if="isPermissions">
      <!-- 上报日志到服务端 -->
      <div>
        <div class="contentview-title">上报日志到服务端</div>
        <div
          class="items-center"
          style="flex-wrap: wrap; justify-content: space-between"
        >
          <van-button type="primary" @click="reportSwitch(true)">
            开启上报
          </van-button>
          <van-button type="primary" @click="reportSwitch(false)"
            >关闭上报
          </van-button>
          <!-- 删除文件 -->
          <van-button type="success" @click="isPermissionsClick(1)">
            删除文件
          </van-button>
          <van-dialog
            v-model:show="removeLog.isShow"
            title="删除日志文件"
            show-cancel-button
            @confirm="removeLogRequest"
          >
            <van-field v-model="removeLog.name" type="text" label="名称" />
            <van-field v-model="removeLog.path" type="text" label="文件路径" />
          </van-dialog>
          <!-- 清空集合数据 -->
          <van-button type="success" @click="isPermissionsClick(4)">
            清空集合数据
          </van-button>
          <van-dialog
            v-model:show="clearCollection.isShow"
            title="清空集合数据"
            show-cancel-button
            @confirm="clearCollectionRequest"
          >
            <van-field
              v-model="clearCollection.name"
              type="text"
              label="集合名称"
            />
          </van-dialog>
          <!-- 下载日志文件 -->
          <van-button type="success" @click="isPermissionsClick(3)">
            下载文件
          </van-button>
          <van-dialog
            v-model:show="downloadFile.isShow"
            title="下载日志文件"
            show-cancel-button
            @confirm="downloadFileRequest"
          >
            <van-field v-model="downloadFile.name" type="text" label="名称" />
            <van-field
              v-model="downloadFile.path"
              type="text"
              label="文件路径"
            />
          </van-dialog>
          <van-button type="success" @click="reportLog"> 测试上报 </van-button>
          <van-button type="success" @click="getConfigInfo">
            获取配置文件
          </van-button>
          <van-button type="success" @click="getCheckFiles">
            获取all文件
          </van-button>

          <van-button type="success" @click="getTrackLog">
            最近3天埋点信息
          </van-button>
          <van-button type="success" @click="getAnalyticsEvent">
            谷歌埋点
          </van-button>
          <!-- 添加过滤 -->
          <van-button type="success" @click="isPermissionsClick(2)">
            添加过滤
          </van-button>

          <van-dialog
            v-model:show="ignoreKey.isShow"
            title="添加过滤"
            show-cancel-button
            @confirm="addIgnoreKey"
          >
            <van-field
              v-model="ignoreKey.text"
              type="text"
              maxlength="999"
              label="关键字"
            />
            <van-radio-group
              v-model="ignoreKey.isRegExp"
              class="items-center"
              style="padding: 10px 15px; justify-content: space-between"
            >
              <van-radio :name="1">非正则</van-radio>
              <van-radio :name="2">正则表达式</van-radio>
            </van-radio-group>
          </van-dialog>
        </div>
      </div>
    </div>

    <!-- intent 协议打开 安卓 app -->
    <div class="items-center" style="justify-content: space-around">
      <a
        :href="`intent://btcdana/from?deep_link_value=${openAndroidPath}#Intent;scheme=btcdana;package=com.btcdana.online;end`"
        >intent BD 安卓调试</a
      >
      <van-dialog
        v-model:show="androidPopup.isShow"
        title="h5 桥接调试"
        show-cancel-button
        @confirm="openAndroid"
      >
        <van-field v-model="androidPopup.path" type="text" label="页面路径" />
        <van-radio-group
          class="items-center"
          style="justify-content: space-around"
          v-model="androidPopup.checked"
        >
          <van-radio name="bd">BD</van-radio>
          <van-radio name="fd">FD</van-radio>
        </van-radio-group>
      </van-dialog>
      <van-button
        type="success"
        @click="
          () => {
            androidPopup.isShow = true;
          }
        "
      >
        安卓调试1
      </van-button>
    </div>

    <!-- 底部跳转 -->
    <div class="items-center jump">
      <div class="jump-btn" @click="jumpPage('coin')">coin</div>
      <div
        class="jump-btn"
        v-if="isPermissions"
        @click="jumpPage('exchangePoints')"
      >
        积分兑换
      </div>
      <div class="jump-btn" v-if="isPermissions" @click="jumpPage('log')">
        日志页面
      </div>
    </div>
  </div>
</template>
<script setup name="home">
import { navigateI18nTo, isiOS, isAndroid } from "@/utils";

import {
  serveReport,
  getServeLog,
  removelog,
  errorkeyoperation,
  trackInfo,
  download,
  analyticsEvent,
} from "~/api/log.ts";
import { showToast } from "vant";
import { useUserStore } from "~~/store/modules/user";
import * as MITO from "@zhj1214/qdjk-web";
import { useLogStore } from "~~/store/modules/log";
import { useGlobalStore } from "~~/store/global";

const file = getOssFileUrl({
  testImg: "/image/qrcode/xyx65.png?btcdanaAppH5Bridge=0426",
});

const route = useRoute();
console.log("页面参数:", route.query);

const userState = useUserStore();
const globalStore = useGlobalStore();
const { WEB_NODE_ENV = "prod" } = useRuntimeConfig().public;

// 是否有权限访问数据
const isPermissions = computed(() => {
  if (userState.$state.email) {
    return (
      route.query.who === "zhj" && userState.$state.email.includes("zhj1214")
    );
  }
  return false;
});

// 生命周期函数
onMounted(() => {});

// 上报日志
const reportLog = () => {
  if (!isPermissions.value) return showToast("暂无权限");
  MITO.log({
    message: "zhj1214",
    tag: "测试",
    level: "high",
    ex: "测试",
  });
};
// 获取日志数据
const getConfigInfo = async () => {
  const res = await getServeLog({
    getConfigData: 1,
  });
  console.log("配置文件信息:", res);
};
// 获取根目录下所有文件
const getCheckFiles = async () => {
  const res = await getServeLog({
    checkFiles: "zhj_all_file",
  });
  console.log("获取根目录下所有文件:", res);
};

/************************************* 打开安卓调试 *************************************/
const getAnalyticsEvent = async () => {
  const res = await analyticsEvent();
  console.log("埋点:", res);
};

// 获取埋点数据
const getTrackLog = async () => {
  const res = await trackInfo({
    pageNumber: 1,
    pageSize: 999999,
    // path: "/lottery-money",
    // granularity: "day",
  });
  console.log("埋点:", res);
};

/************************************* 打开安卓调试 *************************************/
const androidPopup = reactive({
  isShow: false,
  path: "http://192.168.88.xx:3000",
  checked: "bd",
});

const openAndroidPath = ref(
  `${process.client ? window.location.href : ""}&hiddenBar=1`
);

const openAndroid = () => {
  if (process.client && window) {
    androidPopup.isShow = false;
    let cur_u = "";
    if (androidPopup.path != "http://192.168.88.xx:3000") {
      cur_u = androidPopup.path || window.location.href;
    } else {
      cur_u = window.location.href;
    }
    console.log("cur_u: ", cur_u);

    if (androidPopup.checked == "bd") {
      window.location.href = `btcdana://btcdana:8888/from?deep_link_value=${cur_u}${
        cur_u.includes("?") ? "&" : "?"
      }hiddenBar=1`;
    } else if (androidPopup.checked == "fd") {
      window.location.href = `indone://indone:8888/from?deep_link_value=${cur_u}${
        cur_u.includes("?") ? "&" : "?"
      }hiddenBar=1`;
    }
  }
};
/************************************* 清空集合 *************************************/
const clearCollection = reactive({
  isShow: false,
  name: "",
  path: "",
});
const clearCollectionRequest = () => {
  if (!clearCollection.name) return showToast("参数不正确");
  removelog({
    errorId: "all_zhj",
    collectionName: clearCollection.name,
  }); // 服务器上文件格式出错,删除文件,或者直接调接口
};

/************************************* 删除日志文件 *************************************/
const removeLog = reactive({
  isShow: false,
  name: "",
  path: "",
});

const removeLogRequest = () => {
  if (!removeLog.name && !removeLog.path) return showToast("参数不正确");
  removelog({
    errorId: "all_zhj",
    dbName: removeLog.name,
    filePath: removeLog.path,
  }); // 服务器上文件格式出错,删除文件,或者直接调接口
};

/************************************* 下载文件 *************************************/
const downloadFile = reactive({
  isShow: false,
  name: "",
  path: "",
});

const downloadFileRequest = async () => {
  if (!downloadFile.name && !downloadFile.path) return showToast("参数不正确");
  const response = await download({
    id: "all_zhj",
    fileName: downloadFile.name,
  });

  console.log(response);
  const url = window.URL.createObjectURL(response);
  const a = document.createElement("a");
  a.href = url;
  a.download = downloadFile.name;
  document.body.appendChild(a);
  a.click();
  a.remove();
  window.URL.revokeObjectURL(url);
};

// 1: 删除  2: 过滤; 3: 下载 4.清空
const isPermissionsClick = (val) => {
  if (isPermissions.value) {
    if (val == 1) {
      removeLog.isShow = true;
    } else if (val == 2) {
      ignoreKey.isShow = true;
    } else if (val == 3) {
      downloadFile.isShow = true;
    } else if (val == 4) {
      clearCollection.isShow = true;
    }
  } else {
    showToast("暂无权限");
  }
};

// 过滤关键字
const ignoreKey = reactive({
  isShow: false,
  text: "",
  isRegExp: 1,
});
const addIgnoreKey = () => {
  if (!ignoreKey.text) return showToast("请输入关键字");
  // 去重
  const uselog = useLogStore();
  if (uselog.$state.ignoreDynamics.length > 0) {
    if (
      uselog.$state.ignoreDynamics.findIndex((e) => e == ignoreKey.text) != -1
    ) {
      return showToast("重复过滤");
    }
  }

  // 1: 不是  2: 是;   new RegExp('^abc')
  if (ignoreKey.isRegExp == 2) ignoreKey.text = `RegExp:${ignoreKey.text}`;

  errorkeyoperation({
    text: ignoreKey.text,
  }).then((res) => {
    showToast(res);
  });
};
/**
 * @description: 日志上报开关
 * @param {*} isOpen
 */
const reportSwitch = (isOpen) => {
  if (isPermissions.value) {
    serveReport({
      isOpenLogReport: isOpen,
    }).then((res) => {
      showToast(res.msg);
    });
  } else {
    showToast("暂无权限");
  }
};

// 点击-页面跳转
const jumpPage = async (val, isApp = false, params) => {
  if (val === "balance") {
    navigateI18nTo({
      path: "/mvp/assetDetails",
    });
  } else if (val === "mining") {
    navigateI18nTo({ path: "/mvp/mining" });
  } else if (val === "coin") {
    navigateI18nTo({
      path: "/mvp/coin/coin",
    });
  } else if (val === "exchangePoints") {
    navigateI18nTo({
      path: "/mvp/exchangePoints",
    });
  } else if (val === "web") {
    navigateI18nTo({
      path: "/webview",
      query: {
        src: `https://${pageData.jumpUrl}`,
      },
    });
  } else if (val === "log") {
    navigateI18nTo({
      path: "/log/errorlog",
      query: {
        who: "zhj",
      },
    });
  }
};

// 上传图片
// params: Parameters<typeof uploadFileStream>[0] & {
//     type: 1 | 2 | 3; // 1: 身份证正面 2: 身份证反面 3" 手持身份证
//   }
const uploadFileStream = async (params) => {
  const nuxtApp = useNuxtApp();

  try {
    // 先图片压缩一下
    const image = await compressImage(params.image); //  as File;

    // 图片大小不能超过 1 M
    if (image.size > 1024 * 1024) {
      showToast(
        nuxtApp.$i18n.t("version_1_0_0.imageSizeCannotExceed", {
          num: 1,
        })
      );
      return;
    }

    if (params.type === 1) {
      if (this.firstLoading) {
        return;
      }

      this.firstLoading = true;
    } else if (params.type === 2) {
      if (this.lastLoading) {
        return;
      }

      this.lastLoading = true;
    } else if (params.type === 3) {
      if (this.threeLoading) {
        return;
      }

      this.threeLoading = true;
    }

    const result = await uploadFileStream({
      ...params,
      image,
    });

    if (result.code === 200) {
      if (params.type === 1 && result.data) {
        this.ruleForm.firstPic = result.data;
      } else if (params.type === 2 && result.data) {
        this.ruleForm.lastPic = result.data;
      } else if (params.type === 3 && result.data) {
        this.ruleForm.threePic = result.data;
      }
    } else {
      showToast(result.data.errors);
    }
  } catch (error) {
    console.log(error);
  } finally {
    if (params.type === 1) {
      this.firstLoading = false;
    } else if (params.type === 2) {
      this.lastLoading = false;
    } else if (params.type === 3) {
      this.threeLoading = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.home {
  /* 禁止在整个页面范围内的溢出回弹效果 */
  overscroll-behavior-y: none !important;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;

  .contentview {
    margin: 0 16 * 2px;

    &-title {
      font-size: 22 * 2px;
      font-weight: 666;
      margin: 10 * 2px;
    }
  }

  .jump {
    position: fixed;
    bottom: env(safe-area-inset-top);
    bottom: constant(safe-area-inset-top);
    bottom: 44px;
    left: 0;
    width: 100vw;
    justify-content: space-around;

    &-btn {
      padding: 10 * 2px 20 * 2px;
      background-color: #007bff;
      border-radius: 100px;
      text-align: center;
      font-size: 16 * 2px;
      color: #fff;
    }
  }
}
</style>
